package com.hmall.order.web;

import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDto;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.ThreadLocalUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RestController
@RequestMapping("order")
public class OrderController {

   @Autowired
   private IOrderService orderService;
   @Autowired
   private RabbitTemplate rabbitTemplate;

   @GetMapping("{id}")
   public Order queryOrderById(@PathVariable("id") Long orderId) {
      System.out.println(ThreadLocalUtils.getTl());
//      创建消息
      Message msg = MessageBuilder.withBody(orderId.toString().getBytes(StandardCharsets.UTF_8))
              .setHeader("delay",1800000).build();
//      消息Id封装到correlationData中
      CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
//发送消息
      rabbitTemplate.convertAndSend("direct.order","order.delay.queue",msg,correlationData);
      return orderService.getById(orderId);
   }

   /**
    * 创建订单
    * @return
    */
   @PostMapping
   public Long queryPost(@RequestBody OrderDto orderDto){
      Long orderById = orderService.getOrderById(orderDto);
      return orderById;
   }


}
